# coding=UTF-8
import configparser
#编写bat脚本，删除旧程序，运行新程序
import requests
import json
import logging
import subprocess
import os
import sys
logging.basicConfig(level=logging.DEBUG,
                    filename='./error.log',
                    filemode='a',
                    format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

# def writeUpgrade1(exe_name):
#     if os.path.isfile("upgrade.bat"):	#判断是否有upgrade.bat这个文件，有就删除
#         os.remove("upgrade.bat")
#     # if os.path.isfile("update/核桃夹.exe"):  # 判断是否有更新问卷，有运行
#     #     startupdate()
#     #     return
#     b = open("upgrade.bat", 'w')
#     TempList = "@echo off\n"
#     TempList += "if not exist" + ' .\\update\\' + exe_name + " exit \n"  # 判断是否有新版本的程序，没有就退出更新。
#     TempList += "echo 正在更新至最新版本...\n"
#     #TempList += "timeout /t 1 /nobreak\n"  # 等待3秒
#     TempList += "xcopy  .\\update\\  .\\ /s /e /Y \n"  # 复制新版本程序
#     TempList += "echo 更新完成，正在启动...\n"
#     #TempList += "timeout /t 3 /nobreak\n"
#     TempList += "start .\\" + exe_name + " \n"
#     TempList += "del .\\update\\" + exe_name + " \n"  # 删除旧程序
#     TempList += " exit"
#     b.write(TempList)
#     b.close()
#     subprocess.Popen("upgrade.bat") #不显示cmd窗口
    #os.system('start upgrade.bat')  # 显示cmd窗口

# def newUpdate(exe_name):
#     if os.path.isfile("upgrade.bat"):	#判断是否有upgrade.bat这个文件，有就删除
#         os.remove("upgrade.bat")
#     b = open("upgrade.bat", 'w')
#     TempList = "@echo off\n"
#     TempList += "if not exist" + ' .\\update\\' + exe_name + " exit \n"  # 判断是否有新版本的程序，没有就退出更新。
#     TempList += "start .\\update\\" + exe_name + " \n"
#     #TempList += "timeout /t 1 /nobreak\n"  # 等待1秒
#     TempList += "exit"
#     b.write(TempList)
#     b.close()
#     subprocess.Popen("upgrade.bat") #不显示cmd窗口
    #os.system('start upgrade.bat')  # 显示cmd窗口
# def startupdate():
#     if os.path.isfile("update/htj.exe"):	#判断是否有更新文件，有运行
#         a = open("upgrade.bat", 'w')
#         TempList1 = "@echo off\n"
#         TempList1 += "start .\\update\\htj.exe \n"
#         TempList1 += "del .\\update\\htj.exe \n"  # 删除旧程序
#         TempList1 += " exit"
#         a.write(TempList1)
#         a.close()
#         #subprocess.Popen("upgrade.bat") #不显示cmd窗口
#         os.system('start upgrade.bat')  # 显示cmd窗口
#         return True
#     return False
#startupdate()
def checkVersion(): #检查版本
    try:
        url = r'http://hetaojia.corp.hetao101.com/getversion'
        version = json.loads(requests.get(url,timeout=(2, 5)).text)['data'][-1]
        
        #print("获取版本成功"+str(version))
    except Exception as e:
        logging.error("******error******"+str(e))
        return -1
    return version

# def goupdate(version):
#     value = json.loads(requests.get('http://hetaojia.corp.hetao101.com/getupdate?version=' + version).text)['data']
#     logging.debug(len(value))
#     for i in range(len(value)):
#         response = requests.get('http://hetaojia.corp.hetao101.com/tmp/' + value[i]['filename'])
#         houz = value[i]['filename'].split(".")[-1]
#         if houz=="exe":
#             with open("update/" + value[i]['filename'].split("_")[1] + "." + houz, "wb") as f:
#                 f.write(response.content)
#         elif houz=="ini":
#             with open( value[i]['filename'].split("_")[1] + "." + houz, "wb") as f:
#                 f.write(response.content)
#         elif houz=="js":
#             with open("update/res/js/" + value[i]['filename'].split("_")[1] + "." + houz, "wb") as f:
#                 f.write(response.content)
#         else:
#             with open("update/res/" + value[i]['filename'].split("_")[1] + "." + houz, "wb") as f:
#                 f.write(response.content)
#     #writeUpgrade1("核桃夹.exe")
#     newUpdate("htj.exe")

def getoldversion():
    config = configparser.ConfigParser()  # 类实例化
    path = r'.\\version.ini'
    config.read(path)
    version = config['select']['version']  # 获取版本号
    return version
def updateApp():
    config = configparser.ConfigParser()  # 类实例化
    path = r'.\\version.ini'
    config.read(path)
    version = config['select']['version']  # 获取版本号
    newVersion = checkVersion()['version']	#获取新版本号

    if version < newVersion:	#判断当前程序是否是最新版本
        print('当前版本：', version, '\t最新版本：', newVersion)
        return True
    return False





def run_updater():
    print("启动更新程序流程开始")
    try:
        # 获取当前可执行文件/脚本的目录（兼容打包后和未打包状态）
        if getattr(sys, 'frozen', False):
            # 打包后的环境（exe运行时）
            current_dir = os.path.dirname(sys.executable)
            print(f"检测到打包环境，当前目录：{current_dir}")
        else:
            # 未打包的脚本环境
            current_dir = os.path.dirname(os.path.abspath(__file__))
            print(f"检测到脚本环境，当前目录：{current_dir}")

        # 构建updater.exe的完整路径
        updater_path = os.path.join(current_dir, "updater.exe")
        updater_path = os.path.normpath(updater_path)  # 标准化路径（处理斜杠问题）
        print(f"更新程序完整路径：{updater_path}")

        # 检查文件是否存在
        if not os.path.exists(updater_path):
            print(f"错误：更新程序不存在 - {updater_path}")
            return False

        # 检查文件是否可执行
        if not os.access(updater_path, os.X_OK):
            print(f"错误：没有执行权限 - {updater_path}")
            return False

        # 运行程序（使用Popen而非run，避免阻塞并兼容后台运行）
        print(f"尝试启动更新程序...")
        process = subprocess.Popen(
            updater_path,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            creationflags=subprocess.CREATE_NEW_CONSOLE  # 强制创建新窗口，方便查看更新程序输出
        )

        # 非阻塞检查是否启动成功
        try:
            # 超时检测（1秒内无错误视为启动成功）
            stdout, stderr = process.communicate(timeout=1)
            if stderr:
                print(f"更新程序启动警告：{stderr.decode('utf-8', errors='ignore')}")
        except subprocess.TimeoutExpired:
            # 超时通常表示程序正常运行中
            print("更新程序已成功启动")
            return True

        return True

    except subprocess.CalledProcessError as e:
        print(f"程序运行出错，返回码：{e.returncode}")
        print(f"错误输出：{e.stderr.encode('utf-8', errors='ignore')}")
    except Exception as e:
        print(f"启动更新程序时发生异常：{str(e)}")
    return False



